<template>
	<view class="content">
		<iframe allow="camera *;microphone *; display-capture" allowfullscreen="true" border="0" v-if="isVideoLive" webkitallowfullscreen="true" mozallowfullscreen="true" :src="url" frameborder="0" width="100%" height="100%"></iframe>
		<!-- <view class="back" @click="onBack">
			<tui-icon name="home-fill" :size="34" color="#999"></tui-icon>
		</view>
		<view class="back" @click="qiandao" style="bottom: 46vh;right: 30rpx;z-index: 999999;">
			<image src="../../static/qiandao_1.png" mode="" style="width: 100rpx;height: 100rpx;"></image>
		</view> -->
		<tui-login :show="show"  @close="guanbi"></tui-login>
		<tui-sgin :time="countdown" v-if="isSign"  @finish="endOfTime"></tui-sgin>
		<tui-xuanfu></tui-xuanfu>
		<view :class="bottomshow?'showYhq fade-in':'showYhq'">
			<view class="list" v-if="coupon_data.coupon_type==3">
				<view class="title text_one">{{coupon_data.name}}</view>
				<view class="duihuan flex flex-center">
					<view class="center">{{parseInt(coupon_data.price)}}</view>
					<view class="yuan">张</view>
				</view>
				<view class="tiaojian">仅兑换商品可用</view>
				<!-- <view class="time">{{coupon_data.start_time}}至{{coupon_data.end_time}}</view> -->
				<view class="btn flex flex-align flex-center" @click="tui.dianji(getYhq)">立即领取</view>
			</view>
			<view class="list yhlist" v-else>
				<view class="title text_one">{{coupon_data.name}}</view>
				<view class="duihuan flex flex-center">
					<view class="center">{{parseInt(coupon_data.price)}}</view>
					<view class="yuan">元</view>
				</view>
				<view class="tiaojian">适用于部分商品</view>
				<!-- <view class="time">{{coupon_data.start_time}}至{{coupon_data.end_time}}</view> -->
				<view class="btn flex flex-align flex-center" @click="tui.dianji(getYhq)">立即领取</view>
			</view>
		</view>
		<tui-modal :show="modal" background='transparent' @cancel="modal=false" :custom="true">
			<view class="imaggs">
				<image src="/static/zibo_03.png" mode=""></image>
				<view class="flex flex-align flex-center" style="margin-top: 10rpx;" @click="modal=false">
					<tui-icon name="close" :size="28" class="#fff"></tui-icon>
				</view>
			</view>
		</tui-modal>
		<tui-modal :show="jiangli" background='transparent' @cancel="jiangli=false" :custom="true">
			<view class="jiangliBg">
				<view class="flex flex-align flex-center" v-if="receiveInfo.type==0">
					<image src="/static/zibo_08.png" mode=""></image>
					获得 <view class="price">+{{receiveInfo.value}}</view>增寿豆
				</view>
				<view class="flex flex-align flex-center" v-else>
					奖励发放中,请稍后查收
				</view>
			</view>
			<view class="flex flex-align flex-center" style="margin-top: 20rpx;" @click="jiangli=false">
				<tui-icon name="close" :size="28" class="#fff"></tui-icon>
			</view>
		</tui-modal>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				isPlaySource: false, //是否有播放源
				isVideoLive: false, //是否是直播
				isAutoplay: true, //是否自动播放
				videoMsg: '', //video消息
				currentUrl: '', //播放路径
				showControlbar: true,
				timer:null,
				url:'',
				image:'',
				id:'',
				course_name:'',
				dataInfo:'',
				show:false,
				heartbeatInterval:20000, // 20 秒
				heartbeatTimer:null,
				ws:null,
				socket:null,
				is_open_socket:false,
				reconnectTimeOut:null,
				ticket_id:'',
				bottomshow:false,
				coupon_data:'',
				user_id:'',
				isSign:false,
				countdown:'',
				live_status:'',
				modal:false,
				jiangli:false,
				receiveInfo:''
			}
		},
		
		onLoad(e) {
			let that = this
			this.getJianting()
			if(this.tui.isLogin()){
				that.dataInfo = e
				that.getStatus()
			}else{
				uni.setStorageSync('refCode', e.inviter_code)
				uni.setStorageSync('zhiboid', e.zhiboid)
				uni.redirectTo({
					url: '/pages/login/login'
				})
			}
			// this.url =uni.getStorageSync('zhiboUrl')
		},
		// #ifdef MP
		onShareAppMessage() {
			return {
				title:'分享海报',
				path:'/pages/home/home?inviter_code='+uni.getStorageSync('inviter_code')+'&zhiboid='+this.id,
				imageUrl:this.image||'/static/logo.jpg'
			};
		},
		// #endif
		onShow() {
			let that = this
			that.isSign = false
			that.isVideoLive = true
			if(that.tui.isLogin()){
				// that.getDjs()
				that.tui.TongjiLive(1, this.id)
			}
		},
		onHide() {
			// alert(2222)
			let that = this
			if(that.is_open_socket){
				that.ws.close()
			}
			that.is_open_socket = false
			that.isVideoLive = false
			if(uni.getStorageSync('lookLive')==1){
				that.tui.TongjiLive(2, this.id)
			}
			
		},
		onBackPress() {
			// alert(3333)
			let that = this
			that.isVideoLive = false
			if(uni.getStorageSync('lookLive')==1){
				that.tui.TongjiLive(2, this.id)
			}
		},
		onUnload() {
			// alert(4444)
			let that = this
			if(that.is_open_socket){
				that.ws.close()
			}
			that.is_open_socket = false
			that.isVideoLive = false
			if(uni.getStorageSync('lookLive')==1){
				that.tui.TongjiLive(2, this.id)
			}
		},
		methods: {
			onBack(){
				uni.switchTab({
					url:'/pages/home/home'
				})
				// uni.navigateTo({
				// 	url:'/pages/MyOrderList/MyOrderList'
				// })
			},
			getYhq(){
				let that = this
				that.tui.addrequest("coupon/receive", "POST", {coupon_id:Number(that.coupon_data.coupon_id),source:'live',layer:Number(that.coupon_data.push_log_id)}, false, false, false).then((res) => {
					if(res.code==0){
						that.modal = true
						that.bottomshow = false
					}
				}).catch((res) => {
					
				})
			},
			qiandao(){
				let that = this
				that.tui.addrequest("reward/receive", "POST", {room_id:Number(that.dataInfo.room_id)}, false, false, true).then((res) => {
					if(res.code==0){
						that.isSign = false
						that.jiangli = true
						that.receiveInfo = res.data
					}
				}).catch((res) => {
					if(res.code==10011){
						that.isSign = false
						that.getTime()
					}
				})
			},
			onMessage(e) {
				let that = this
				that.tui.href('/pages/ConfirmOrder/ConfirmOrder?order_no='+e.detail.data)
			  console.log('Received message from web page:', e.detail.data);
			},
			
			endOfTime(data){
				let that = this
				if(data){
					that.qiandao()
				}
			},
			getJianting(){
				let that = this
				window.addEventListener('message', function (event) {
				    // 获取消息内容
				    var messageEvent = event.data;
				 
				    // 检查 messageEvent 是否存在或者是一个对象类型。
				    if (!messageEvent || typeof messageEvent !== 'object') {
				        // 输出错误信息 'Received invalid message event:'，并将 messageEvent 的值打印出来。
				        console.error('Received invalid message event:', messageEvent);
				        // 返回（结束当前函数的执行）。
				        return;
				    }
				    // 检查消息类型是否为 "vhOpenHref"，并提取URL
				    if (messageEvent.type === 'vhOpenHref' && typeof messageEvent.data === 'string') {
				 
				        // 在移动端浏览器上运行的逻辑
						that.tui.href('/pages/GoodsDetails/GoodsDetails?id='+that.getParam(messageEvent.data,'id'))
				         // window.location.href = messageEvent.data;
				 
				    } else {
						
				    }
				});
			},
			getParam(path, name) {
				  var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");   
				  if (reg.test(path))  
				  return unescape(RegExp.$2.replace(/\+/g, " ")); 
				  return "";    
			},
			getDjs(){
				let that = this
				that.tui.request("api.auth.live/enter_room", "POST", {room_id:that.dataInfo.room_id}, false, false, true).then((res) => {
					if(res.code==1){
						that.user_id = res.data.user_id
						that.live_status = res.data.live_status
						let url = "wss://socket.zzcyx1688.cn/ws"
						// that.socketIo.connectSocketInit(url)
						that.getscokt(url)
						if(res.data.live_status==2){
							if(res.data.coupon){
								that.coupon_data = res.data.coupon
								that.coupon_data.is_use_coupon==0?that.bottomshow=true:that.bottomshow=false
							}
							
						}
					}
				}).catch((res) => {
							
				})
			},
			getTime(){
				let that = this
				that.tui.addrequest("reward/times", "POST", {room_id:Number(that.dataInfo.room_id)}, false, false, true).then((res) => {
					if(res.code==0){
						if(!res.data.is_receive){
							that.countdown = res.data.times
							that.isSign = true
							// setTimeout(()=>{
							// 	that.qiandao()
							// },(res.data.times-60)*1000)
						}
						
					}
				}).catch((res) => {
					
				})
			},
			getList(){
				let that = this
				let data = {}
				that.tui.request("api.auth.room/playbackList", "POST", {page:that.page}, false, false, true).then((res) => {
					if(res.code==1){
						res.data.list.map(item=>{
							if(that.id==item.id){
								that.url = item.url
								uni.setStorageSync('zhiboStatus',item)
								data.title = uni.getStorageSync('shareTitle')
								data.desc = item.name
								data.share_img = item.cover
								uni.setStorageSync('shareZhibo', data)
								that.tui.wxShare(1,item.id)
								that.ticket_id = item.room_id
								
							}
						})
					}
				}).catch((res) => {
					
				})
			},
			guanbi(){
				let that = this
				that.show = false
				that.getBijiao()
			},
			getBijiao(){
				let that = this
				that.id=that.dataInfo.zhiboid
				that.getList()
			},
			getStatus(){
				let that = this
				that.getBijiao()
				return
				that.tui.request("api.auth.center/phoneStatus", "POST", {}, false, false, true).then((res) => {
					if(res.code==1){
						if(res.data.is_phone==2){
							that.show = true
						}else{
							that.getBijiao()
						}
					}
				}).catch((res) => {
			
				})
			},
			getscokt(url){
				let that = this
				that.ws = new WebSocket(url);
				try {
				    // ws连接成功
				    that.ws.onopen = function () {
				        console.log("WebSocket Server [" + url + "] 连接成功！");
						that.is_open_socket = true
						clearTimeout(that.reconnectTimeOut)
				        that.startHeartbeat();
						let data = {'type':'login','user_id':that.user_id,'room_id':that.ticket_id}
						that.ws.send(JSON.stringify(data));
						if(that.live_status==2){
							that.getTime()
						}
				    };
				    // ws连接关闭
				    that.ws.onclose = function () {
				        if (that.ws) {
				            that.ws.close();
				            that.ws = null;
				        }
				        console.log("WebSocket Server [" + url + "] 连接关闭！1");
				        that.stopHeartbeat();
						if(that.is_open_socket){
							that.reconnectTimeOut = setTimeout(()=>{
								that.getscokt(url);
							},3000)
						}
				    };
				    // ws连接错误
				    that.ws.onerror = function () {
				        if (that.ws) {
				            that.ws.close();
				            that.ws = null;
				        }
				        console.log("WebSocket Server [" + url + "] 连接关闭！2");
				        that.stopHeartbeat();
				    };
				    // ws数据返回处理
				    that.ws.onmessage = function (result) {
						let rest =JSON.parse(result.data)
						console.log(result)
						if(rest.type=='ping'){
							let data = {'type':'pong'}
							that.ws.send(JSON.stringify(data));
						}else if(rest.type=='send_red_rain'){
							console.log(rest.type)
							
						}else if(rest.type=='send_coupon'){
							that.bottomshow = true
							that.coupon_data = rest
						}else if(rest.type=='cancel_coupon'){
							that.bottomshow = false
							that.coupon_data = ''
						}else if(rest.type=='start_live'){
							that.live_status=2
							that.ws.close()
							that.is_open_socket = true
						}else if(rest.type=='end_live'){
							that.ws.close()
							that.is_open_socket = false
							that.isSign = false
							that.bottomshow = false
							that.coupon_data = ''
						}
						
						// else if(rest.type=="ended"){
						// 	that.gameStatus = 3;
						// 	let onNumber = Math.round(that.redNumber/(that.redBox.length/5));
						// 	that.stars.fill('../../static/redBoxRain/starOn.png',0,onNumber);
						// 	that.click_red_rain_amount = rest.data.user_join_red_rain_info.click_red_rain_amount
						// }
						
				    };
				} catch (e) {
					console.log(e)
				}
			},
			// 启动心跳定时器
			startHeartbeat() {
				var that = this
			    that.heartbeatTimer = setInterval(function () {
			        if (that.ws && that.ws.readyState === WebSocket.OPEN) {
			            let data = {'type':'pong'}
			            that.ws.send(JSON.stringify(data));
			        }
			    }, that.heartbeatInterval);
			},
			// 停止心跳定时器
			stopHeartbeat() {
				var that = this
			    clearInterval(that.heartbeatTimer);
			},
		}
	}
</script>
 
 
<style lang="scss" scoped>
	.content {
		width: 100vw;
		height: 100vh;
		display: flex;
		flex-direction: column;
		.player-content {
			position: relative;
			width: 100%;
			height: 450rpx;
			display: flex;
			background-size: 100% 100%;
 
			.live-player {
				width: 100%;
				height: 100%;
				position: relative;
			}
		}
	}
	.imaggs{text-align: center;
		image{width: 460rpx;height: 300rpx;}
	}
	.jiangliBg{background: url('@/static/zibo_04.png') no-repeat;background-size: 100% 100%;width: 460rpx;height: 400rpx;
		margin: 0 auto;position: relative;
		.flex{color: #FE7431;font-size: 14px;text-align: center;position: absolute;bottom: 40rpx;left: 50%;width: 360rpx;margin-left: -180rpx;background: #fff;border-radius: 20rpx;height: 80rpx;
			image{width: 40rpx;height: 40rpx;margin-right: 10rpx;}
			view{font-weight: bold;font-size: 16px;margin: 0 4rpx;}
		}
	}
	.showYhq{position: fixed;z-index: 999;bottom: 120rpx;right: -270rpx;
		.list{width: 272rpx;height: 388rpx; background: url('@/static/zibo_01.png') no-repeat;background-size: 100% 100%;text-align: center;padding-top: 80rpx;padding-bottom: 20rpx;
			.title{color: #F8E1BA;font-size: 14px;width: 220rpx;margin: 0 auto;}
			.duihuan{margin: 15rpx 0 25rpx;
				align-items: flex-end;color:#F8E1BA;
				.center{font-size: 30px;padding: 0 10rpx;line-height: .8;font-weight: bold;min-width: 60rpx;}
				.right{font-weight: bold;}
			}
			.tiaojian{color: #F8E1BA;font-size: 12px;margin: 14rpx 0 6rpx;line-height: 1;}
			.time{font-size: 10px;color: #8B2D21;width: 160rpx;margin: 0 auto;}
			.btn{width: 168rpx;height: 50rpx;background: #F0C59F; background: url('@/static/zhibo_08.png') no-repeat;background-size: 100% 100%;margin: 50rpx auto 0;line-height: 38rpx;}
		}
		.yhlist{ background: url('@/static/zibo_02.png') no-repeat;background-size: 100% 100%;}
	}
	.showYhq.fade-in {
	    animation: fadeIn 1s ease-in-out forwards;
	}
	.back{
		position: fixed;
		right: 20rpx;
		bottom:40vh;
		display: flex;
		align-items: center;
		justify-content: center;z-index: 99999;
		width: 100rpx;
		height: 100rpx;
		// 返回
		.back-one{
			display: flex;
			align-items: center;
			justify-content: center;
			width: 50rpx;
			height: 50rpx;
			background-color: rgba(0,0,0,0.3);
			border-radius: 100%;
			text{
				display: flex;
				width: 20rpx;
				height: 20rpx;
				border-left: 2rpx solid #FFFFFF;
				border-bottom: 2rpx solid #FFFFFF;
				transform: rotate(45deg);
			}
		}
		.action{
			background-color: transparent;
			text{
				border-color: #555555;
			}
		}
	}
	//播放器弹出工具
	.player-tool {
		width: 100%;
		height: 60rpx;
		background-image: linear-gradient(0deg, rgba(0, 0, 0, .6), transparent);
		display: flex;
		align-items: center;
		justify-content: space-between;
		position: absolute;
		left: 0;
		padding: 0 45rpx;
		transition: all 0.3s;
		.tools {
			height: 100%;
			width: auto;
			display: flex;
			align-items: center;
 
			.full-screen {
				height: 100%;
				display: flex;
				align-items: center;
				justify-content: center;
 
				.iconfont {
					color: #fff;
					font-weight: bold;
 
				}
			}
 
			.cruise {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-left: 25rpx;
 
				.iconfont {
					color: #E45A3E;
					font-size: 45rpx;
				}
			}
		}
 
	}
	
	@keyframes fadeIn {
	    from {
	        opacity: 0;
			right: -270rpx;
	    }
	    to {
	        opacity: 1;
			right: 20rpx;
	    }
	}
</style>
